import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useRoute,useRouter } from 'vue-router'


export const useRouteStore = defineStore('useRoute', () => {
  const routes = ref([])
  
  function setRoutes(value){
	  routes.value = value
  }
  
  const route = useRoute();
  const router = useRouter();
  const breadcrumbName = ref([])

  function setBreadcrumb(name: any) {
	 breadcrumbName.value=name
  }
  const tabs = ref([]);
  const editableTabsValue = ref('');
  const editIndex = ref(0)
  function setTab(tab: any) {
	  editableTabsValue.value = tab.title;
	  let nohas = ref(true);
	  tabs.value.forEach((item,index)=>{
		  if(item.title === tab.title){
			  nohas.value = false;
			  return;
		  }
	  })
	  if(nohas.value){
		  tabs.value.push(tab)
		  editIndex.value = tabs.value.indexOf(tab)
	  }
	  
  }
  function removeTab(tab: any) {
  	  tabs.value.forEach((item,index)=>{
  		  if(item.title === tab.title){
			  tabs.value.splice(tabs.value.indexOf(item), 1); 
			  // tabs.value.pop(item)
			  console.log("inex:"+index)
			  console.log("editIndex:"+editIndex.value)
			  if(tabs.value.length > 0){
				  if(editIndex.value >= index && tabs.value.length > 0){
					  editableTabsValue.value = tabs.value[tabs.value.length-1].title
					  editIndex.value=tabs.value.length-1
					  router.push(tabs.value[tabs.value.length-1].path)
				  }else if(editIndex.value === index && tabs.value.length === 0){
					  removeAllTab()
				  }
			  }
  			  return;
  		  }
  	  })
  }
  function removeAllTab() {
  	  tabs.value = [];
	  editableTabsValue.value = '';
	  editIndex.value=0
	  router.push('/index')
  }
  function removeOtherTab(tab: any) {
	  tabs.value = [];
	  tabs.value.push(tab);
	  editableTabsValue.value = tab.title
	  editIndex.value = tabs.value.indexOf(tab)
  }
  function updateEditIndex(tabTitle){
	  tabs.value.forEach((item,index)=>{
	  		if(item.title === tabTitle){
				editIndex.value = index
	  			return;
	  		}  
	  })
  }
  return {setRoutes, updateEditIndex,routes,route,router,breadcrumbName,setBreadcrumb,setTab,tabs,editableTabsValue,removeTab,removeOtherTab,removeAllTab}
})
